package com.bc.web.controller.admin;

import com.bc.web.model.AdminRole;
import com.bc.web.model.AdminUser;
import com.fs.common.extend.FSController;
import com.fs.common.util.FSDate;
import com.fs.common.util.FSMD5;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;

public class AdminUserController extends FSController{
	
	public void index(){
		setAttr("sidebar", getSession().getAttribute("sidebar"));
		render("index.html");
	}
	
	public void search(){
		Page<AdminUser> items = AdminUser.dao.search(super.getSearchCondition());
		setPageResultToRequest("items", items);
		render("system/adminUserList.html");
	}
	
	public void addPage(){
		setAttr("roleList", AdminRole.dao.selectAll());
		render("system/adminUserAdd.html");
	}
	
	public void updatePage(){
		AdminUser user = AdminUser.dao.findById(getPara("id"));
		setAttr("roleList", AdminRole.dao.selectAll());
		setAttr("adminUser", user);
		render("system/adminUserUpdate.html");
	}
	
	public void add(){
		AdminUser user = getModel(AdminUser.class);
		if(AdminUser.dao.selectByUserName(user.getUserName()) != null){
			renderFail("用户名已存在");
		}else {
			user.setPassword(FSMD5.codeFor(user.getPassword()));
			user.setUpdateTime(FSDate.getDateTime());
			user.setEnable(true);
			user.save();
			renderSuccess();
		}
	}
	
	public void changeEnable(){
		Integer userId = getParaToInt("id");
		AdminUser.dao.changeEnable(userId);
		renderSuccess(false);
	}
	
	public void update(){
		AdminUser user = getModel(AdminUser.class,true);
		String newPassword = getPara("newPassword");
		if(StrKit.notBlank(newPassword)){
			user.setPassword(FSMD5.codeFor(newPassword));
		}
		user.setUpdateTime(FSDate.getDateTime());
		user.update();
		renderSuccess();
	}
	
	public void delete(){
		AdminUser.dao.deleteById(getPara("id"));
		renderSuccess(false);
	}
	
	public void changePasswordPage(){
		render("changePassword.html");
	}
	
	public void changePassword(){
		String userId = getPara("userId");
		String oldPassword = getPara("oldPassword");
		String newPassword = getPara("newPassword");
		AdminUser user = AdminUser.dao.findById(userId);
		if(user.getPassword().equalsIgnoreCase(FSMD5.codeFor(oldPassword))){
			user.setPassword(FSMD5.codeFor(newPassword));
			user.update();
			renderSuccess();
		}else{
			renderFail("旧密码不正确");
		}
	}

}
